/**
 * 从币世界拉取最新消息
 */

const moment = require('moment')
const config = require('../config')
const log4js = require('log4js')
const schedule = require('node-schedule')
const request = require('request-promise')
const Redis = require('ioredis')
const redis = new Redis(config.redis)

// 配置log4js
log4js.configure(config.log4js)
const logger = log4js.getLogger('Upbit')

// 存储最新一条消息
let latestNews = null
let url = 'https://api-manager.upbit.com/api/v1/notices?page=1&per_page=1'

async function getNews () {
  try {
    let res = await request({url: url, json: true})
    if (res.success) {
      let news = res.data.list[0]
      if (latestNews && latestNews.title === news.title) {
        return null
      } else {
        latestNews = {
          type: 4,
          source: 'Upbit',
          title: news.title,
          content: '',
          time: moment(news.created_at).utcOffset(8).format('YYYY-MM-DD HH:mm:ss')
        }
        return latestNews
      }
    } else {
      throw new Error(res.message)
    }
  } catch (e) {
    logger.error(e.message)
    return null
  }
}

/**
 * 每4秒执行一次查询
 */
schedule.scheduleJob('*/4 * * * * *', async () => {
  let news = await getNews()
  news && console.log(news)
  news && redis.publish('news', JSON.stringify(news))
})
